<?php
            
use app\model\Ad; 
use app\model\Theme; 
use app\model\Poster; 
use app\model\Worker; 
use app\model\Order; 
use app\model\Userdata; 
use app\model\Otherform; 


class Index_Page extends PluginMobilePage {

    //接口梳理：1、主页接口（banner、礼物数、打call数、是否是员工、客片名称、头像、客片结束时间、宣言、打call记录、礼品信息、
    //打赏广告、领取广告与悬浮、顶部图片组在打call上边，裂变图片在样片上边、活动内容在样片下边、按钮增加类型动作）
    function main()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        //李总form表单处理方法
        $config = Theme::format_duoxuan($config);
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        $wk_id = intval($_P['wk_id'])?:0;
        if (!$wk_id || $wk_id==0){
            //重新通过uid以及themeid获取微客信息
            $wk_item = db_get(wk_info,['themeid'=>$themeid,'uid'=>$uid]);
            if ($wk_item){
                $wk_id = $wk_item['id'];
            }
        }
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            $data = [
                'centerimgs'=>$config['centerimgs'],
                'imgs'=>$config['imgs'],//裂变图片字段
                'contentxcx'=>$config['contentxcx'],//小程序内容
            ];
            return_json(1,'未找到微客信息',$data);
        }
        $wk_uid = $wkInfo['uid'];
        //是否是员工
        $isWorker = is_worker($themeid);
        $avatar = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
        if($wk_uid > 0){
            $wkUserInfo = db_get(t_fans, ['themeid' => $themeid, 'uid' => $wk_uid]);
            $avatar = $wkUserInfo['avatar'];
        }else{
            if(!$isWorker){
                $avatar = $fans['avatar']?:'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
            }
        }

        $getavatar = $config['getavatar'];
        if ($fans && $fans['nickname']!='新用户' && $fans['nickname']!='微信用户'){
            $getavatar = 0;
        }
        $getmobile = (int)$config['getmobile'];
        if ($fans && $fans['mobile']){
            $getmobile = 0;
        }

        //是否是员工
        $isWorker = is_worker($themeid);
        $wk_config = $wkInfo['config'];

        //打call列表,展示头像,暂定返回100条数据
        $call_list = WeikeModel::getCallRecordList($themeid,$wk_id, '', 0, 1000);
        if (empty($call_list)){
            $call_list = [];
        }
        foreach ($call_list as &$item){
            if(mb_strlen($item['nickname']) > 5){
                $item['nickname'] = mb_substr($item['nickname'],0,5).'...';
                if (empty($item['nickname'] || $item['nickname'] == null)){
                    $item['nickname'] = '';
                }
                if (empty($item['avatar'] || $item['avatar'] == null)){
                    $item['avatar'] = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
                }
            }
        }
        if($config['wk_show_friend_info_type'] != 2){
            $call_arr = array_chunk($call_list,15);
            $all_length = count($call_arr);
            $change_index = 0;
            $insert_num = 15;
            if($all_length){
                $change_index = $all_length-1;
                $insert_num = 15-count($call_arr[$change_index]);
            }
            //补充完整用户名和头像
            if($insert_num){
                if(empty($call_arr[$change_index])){
                    $call_arr[$change_index] = [];
                }
                for ($i=1; $i<=$insert_num; $i++){
                    array_push($call_arr[$change_index],['id'=>0,'avatar'=>'https://css2020.yixuan.net/2020css/yx2020/images/usera.png','nickname'=>' ','mobile'=>'','created_at'=>'']);
                }
            }
        }else{
            foreach ($call_list as &$v){
                if($v['mobile']){
                    $v['mobile'] = substr($v['mobile'],0,3).'****'.substr($v['mobile'],7);
                }else{
                    $v['mobile'] = '未授权用户';
                }
            }
//            $call_list = array_merge($call_list,$call_list,$call_list);//测试多条数据用
            $call_arr = array_chunk($call_list,7);
        }

        $order_ids = $wk_config['arecord_ids'];
        $buy_list = [];
        if(!empty($order_ids)){
            $buy_list = WeikeModel::getArecordList($themeid,implode(",",$order_ids));
        }
        $can_buy = false;
        $has_buy = false;
        $buyUids = [];
        if(!empty($buy_list)){
            $buyUids = array_column($buy_list,'uid');
        }
        $themyrecord = [];
        if (!empty($buyUids) && $uid && in_array($uid,$buyUids)){
            $has_buy = true;
            //查找record信息
            $record_id = 0;
            foreach ($buy_list as $item){
                if($item['uid'] == $uid){
                    $record_id = $item['id'];
                }
            }
            $themyrecord = WeikeModel::getArecordById($record_id);
        }
        $limit = $config['wk_buy_limit'];
        if($limit > 0){
            if ($uid && !$has_buy && count($buy_list) < $limit){
                $can_buy = true;
            }
        }else if($limit == 0){
            if (!$has_buy){
                $can_buy = true;
            }
        }
        //组装数组
        $content_button_width = $config['wk_content_get_gift_button_width']?:0;
        $content_button_top = $config['wk_content_get_gift_button_top']?:0;
        $shareInfo = '';
        if ($fans){
            $shareInfo = WeikeModel::getShareinfo($fans,$wkInfo);
        }
        $data = [
            'photo'=>$wk_config['photo'],
            'show_type'=>$wk_config['show_type'],
            'call_num'=>$wkInfo['call_num'],
            'gift_num'=>$wkInfo['gift_num'],
            'name'=>$wkInfo['name'],
            'avatar'=>$avatar,
            'end_time'=>$wk_config['end_time'],
            'wk_call_declaration'=>str_replace('#name', $wkInfo['name'], $config['wk_call_declaration']),//打call宣言
            'call_list'=>$call_arr,//打call用户列表
//            'call_gift_list'=>$call_gift_list,//打call礼品信息列表
            'wk_give_gift_ad_img'=>$config['wk_give_gift_ad_img'],//送礼物广告图片
            'wk_get_gift_ad_img'=>$config['wk_get_gift_ad_img'],//领取礼包广告图片
            'wk_get_gift_icon'=>$config['wk_get_gift_icon'],//领取礼包悬浮按钮
            'centerimgs'=>$config['centerimgs'],//顶部图片组字段
            'imgs'=>$config['imgs'],//裂变图片字段
//            'detail'=>$config['content'],
            'contentxcx'=>$config['contentxcx'],//小程序内容
            'is_worker'=>$isWorker,
            'has_buy'=>$has_buy,
            'can_buy'=>$can_buy,
            'wk_give_call_button_img'=>$config['wk_give_call_button_img']?:'https://css2020.yixuan.net/2020css/weike/images/icon5.png',
            'shareinfo'=>$shareInfo,
            'music'=>$wk_config['music_src']?:'',//音乐
            'page_view'=>$wkInfo['page_view'],
            'content_button'=>$config['wk_content_get_gift_button'],//内容中button
            'content_button_width'=>"$content_button_width".'%',//内容中button宽
            'content_button_top'=>"$content_button_top".'rpx',//内容中button距离顶部高度
            'content_button_text'=>$config['wk_content_get_gift_button_text'],//内容中button距离顶部高度
            'has_mobile'=>$fans['mobile']?1:0,
            'has_username'=>$fans['username']?1:0,
            'getmobile'=>$getmobile,
            'getavatar'=>$getavatar,
            'wk_show_slogan'=>$config['wk_show_slogan'],//口号
//            'wk_friend_title'=>$config['wk_friend_title'],//人气标题
//            'wk_gift_title'=>$config['wk_gift_title'],//礼品标题
            'wk_photo_type'=>$config['wk_photo_type']?:0,//类型 1儿童 2婚纱
            'has_case_gift'=>intval($wkInfo['has_case_gift']),//兑换状态 0未兑换 1已兑换
            'gifthexiaoname'=>$config['gifthexiaoname'].'请找工作人员扫码',
            'config'=>$config,
            'other_form'=>'',
            'can_call'=>1,//1可以打call，0不可以打call
            'call_tips'=>'',//打call提示信息
            'has_collect'=>true,
            'wk_photo_show_type'=>$config['wk_photo_show_type']
        ];
        //如果不是员工，第一个人进行绑定
        $ismy = false;
        if($uid && $uid == $wkInfo['uid']){
            $ismy = true;
        }
        if($uid && !$isWorker && $wkInfo['uid'] == 0){
            $bind = WeikeModel::editWkDataByWhere(['id'=>$wk_id],['uid'=>$uid]);
            if($bind){
                $ismy = true;
                $fee = floatval($config['groupprice']);
                $uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
                //如果没有recordid，进行新增;如果有进行修改；
                $record_data = [
                    'uniacid'  => $_G['mpid'],
                    'themeid'  => $themeid,
                    'openid'   => $_G['openid'],
                    'uid'      => $_G['member']['uid'],
                    'nickname' => $fans['nickname'],
                    'avatar'   => empty($fans['avatar']) ? $fans['headimgurl']:$fans['avatar'],
                    'username' => $fans['username'],
                    'mobile'   => $fans['mobile'],
                    'status'   => -2,//虚拟定单
                    'fromuid'  => $_G['member']['uid'],
                    'fopenid'  => $_G['openid'],
                    'workerid'  => intval($wk_config['workerid']),
                ];
                if(!$wkInfo['recordid']){
                    $record_data['addtime'] = TIMESTAMP;
                    $record_data['fee'] = $fee;
                    $record_data['uncode'] = $uncode;
                    $record_data['type'] = 0;
                    $reordid = WeikeModel::addArecord($record_data);
                    //更新pid
                    if ($reordid){
                        WeikeModel::editArecordByWhere(['id'=>$reordid],['pid'=>$reordid]);
                        WeikeModel::editWkDataByWhere(['id'=>$wk_id],['recordid'=>$reordid]);
                    }
                }else{
                    WeikeModel::editArecordByWhere(['id'=>$wkInfo['recordid']],$record_data);
                }
            }
        }
        $data['ismy'] = $ismy;
        if($ismy){
            $data['fromuid'] = $_G['member']['uid'];
        }else{
            $data['fromuid'] = $wkInfo['uid'];
        }
        //判断是否可以打call
        if($data['ismy']){
            $data['can_call'] = 0;
            $data['call_tips'] = '不可以为自己打CALL';
        }else{
            $start = '';
            $end = '';
            if ($config['wk_call_type'] == 0){
                //每人每天打call一次
                $start = date('Y-m-d').' 00:00:00';
                $end = date('Y-m-d').' 23:59:59';
            }
            $call_info = WeikeModel::getCallRecords($themeid,$wk_id,$uid,$start,$end);
            if (!empty($call_info)){
                $data['can_call'] = 0;
                $data['call_tips'] = '您已经为TA打过CALL';
            }
        }
        //打call礼品列表
        $call_gift_list = WeikeModel::getCallGiftList($wk_config['wk_call_gift_group_id']?:0);
        $case_gift_id = 0;
        if($wkInfo['has_case_gift']){
            $case_gift_id = $wk_config['case_gift_id']?:0;
        }
        foreach ($call_gift_list as &$v){
            $v['imgs'] = $v['content'];
            $v['show_num'] = $wkInfo['call_num']>=$v['num_limit']?$v['num_limit']:$wkInfo['call_num'];
            $v['scale'] = $wkInfo['call_num']>=$v['num_limit']?'100%':sprintf("%.1f",$wkInfo['call_num']/$v['num_limit']*100).'%';
            $v['scale_num'] = $wkInfo['call_num']>=$v['num_limit']?100:sprintf("%.1f",$wkInfo['call_num']/$v['num_limit']*100);
            //满足可以兑换，生成核销码保存
            if ($v['scale_num'] >= 100){
                //配置中查询核销码，没有重新生成且保存
                $index = 'case_gift_qrimg_'.$v['id'];
                if($wk_config[$index]){
                    $v['qrimg'] = $wk_config[$index];
                }else{
                    //生成小程序码
                    $scene = MODULE_NAME . "-" . $theme['id'] . "-".$wk_id."-" . $theme['softkey']."-".$v['id'];
                    $inputurl = Poster::CreateScene($system, $scene, $config, 'Worker/pages/w_wkcheck/w_wkcheck');
                    $wk_config[$index] = $inputurl;
                    WeikeModel::editWkDataByWhere(['id'=>$wk_id],['config'=>json_encode($wk_config,JSON_UNESCAPED_UNICODE)]);
                }
            }
            $case_status = 0;
            $case_time = '';
            if($case_gift_id && $case_gift_id == $v['id']){
                $case_status = 1;
                $case_time = $wk_config['case_gift_time'];
            }
            $v['case_status'] = $case_status;
            $v['case_time'] = $case_time;
            if($ismy){
                if(!$wkInfo['has_case_gift'] && $v['scale_num'] == 100 && $case_status == 0){
                    $v['show_type'] = 1;
                    $v['show_desc'] = '立即领取';
                }else if($wkInfo['has_case_gift'] && $v['scale_num'] == 100 && $case_status == 1){
                    $v['show_type'] = 2;
                    $v['show_desc'] = '您已兑换';
                }else if($wkInfo['has_case_gift'] && $v['scale_num'] == 100 && $case_status == 0){
                    $v['show_type'] = 2;
                    $v['show_desc'] = '已领取其他礼品';
                }
            }
        }
        $data['call_gift_list'] = $call_gift_list;
        //按钮信息处理
        $left_array = '';
        $right_array = '';
        //url 1打赏礼物弹窗 2直接打call 3查看支付信息 4表单弹窗 5分享
        if(!$ismy){
            if($config['wk_gift_open']){
                $left_array = ['text'=>$config['wk_button_left_text'],'bg_color'=>$config['wk_button_left_bg_color'],'color'=>$config['wk_button_left_text_color'],'url'=>1];
            }else if($config['wk_call_open'] && !$config['wk_gift_open']){
                $left_array = ['text'=>'为Ta打Call','bg_color'=>$config['wk_button_left_bg_color'],'color'=>$config['wk_button_left_text_color'],'url'=>2];
            }
            if ($has_buy){
                $right_array = ['text'=>'查看支付信息','bg_color'=>$config['wk_button_right_bg_color'],'color'=>$config['wk_button_right_text_color'],'url'=>3];
            }else{
                $right_array = ['text'=>$config['wk_button_right_text'],'bg_color'=>$config['wk_button_right_bg_color'],'color'=>$config['wk_button_right_text_color'],'url'=>4];
            }
        }else{
            $right_array = ['text'=>$config['wk_button_ismy_text'],'bg_color'=>$config['wk_button_right_bg_color'],'color'=>$config['wk_button_right_text_color'],'url'=>5];
        }
        $bottombut = [
            'left'=>$left_array,
            'right'=>$right_array,
        ];
        $data['bottombut'] = $bottombut;
        //查找广告信息
        $data['ad_info'] = Ad::get_ad_info($config,$fans,$themeid,$themyrecord);
        //查找收集信息
        if ($config['wk_call_form_type'] || $config['wk_gift_form_type']) {
            $data["other_form"] = Otherform::getBaseInfoAndInput($system, $theme, $config, $fans);
            //查找是否收集过信息
            $collect_info = Otherform::getItem(['themeid'=>$themeid,'uid'=>$uid]);
            if(empty($collect_info)){
                $data["has_collect"] = false;
            }
        }
        //增加浏览量
        $res = WeikeModel::addPageView($wk_id,$themeid);
        $workerInfo = Worker::getThemeWorkerByUid($wk_config['workerid'],$themeid,1);
        if(!empty($workerInfo)){
            WeikeModel::addWorkerPageView($workerInfo,$themeid);
        }
        if ($res){
            $data['page_view'] = $data['page_view']+1;
        }
        $friendIds = $wk_config['friend_ids']?:[];
        if ($uid && $wkInfo['uid'] && $uid != $wkInfo['uid'] && !$isWorker && !in_array($uid,$friendIds)){
            //执行写入
            array_push($friendIds,$uid);
            $wk_config['friend_ids'] = $friendIds;
            WeikeModel::addFriendNum($wk_id,$themeid,json_encode($wk_config,JSON_UNESCAPED_UNICODE));
        }
        return_json(0,'',$data);
    }

    //2、特权礼包弹窗信息接口：配置信息、购买信息、表单信息、未购买与已购买
    function applyShowInfo(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        //李总form表单处理方法
        $config = Theme::format_duoxuan($config);
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        $wk_id = intval($_P['wk_id'])?:0;
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息');
        }
        //是否是员工
        $isWorker = is_worker($themeid);
        $wk_config = $wkInfo['config'];
        //查找购买的用户头像，只查找已支付状态
        $order_ids = $wk_config['arecord_ids'];
        $buy_list = [];
        if(!empty($order_ids)){
            $buy_list = WeikeModel::getArecordList($themeid,implode(",",$order_ids));
        }
        $buy_num = count($buy_list);
        $can_buy = false;
        $has_buy = false;
        $buyUids = [];
        if(!empty($buy_list)){
            $buyUids = array_column($buy_list,'uid');
            foreach ($buy_list as &$item){
                if(mb_strlen($item['nickname']) > 4){
                    $item['nickname'] = mb_substr($item['nickname'],0,4).'...';
                }
                $item['mobile'] = substr($item['mobile'],0,3).'****'.substr($item['mobile'],7);
            }
        }
        if ($uid && !empty($buyUids) && in_array($uid,$buyUids)){
            $has_buy = true;
        }
        $limit = $config['wk_buy_limit'];
        if($limit > 0){
            if (!$has_buy && count($buy_list) < $limit){
                $can_buy = true;
            }
            $diff = $limit-count($buy_list);
            if ($diff>0){
                for ($i=0; $i<$diff; $i++){
                    array_push($buy_list,['id'=>0,'avatar'=>'https://css2020.yixuan.net/2020css/weike/images/icon30.png','nickname'=>'待领取','mobile'=>'']);
                }
            }
        }else if($limit == 0){
            if (!$has_buy){
                $can_buy = true;
            }
        }
        //form表单
        $form = [
            ['title'=>$config['nametext'],'type'=>'txt','name'=>'nametext','val'=>'','placeholder'=>'请输入'.$config['nametext'],'final_value'=>''],
            ['title'=>$config['mobiletext'],'type'=>'mobile','name'=>'mobiletext','val'=>'','placeholder'=>'请输入'.$config['mobiletext'],'final_value'=>''],
        ];
        if ($config['datetime']){
            $type = 'txt';
            $val = '';
            $maxlength = 0;
            switch ($config['datetimetype']){
                case '1':
//                    $type = 'number';
                    $maxlength = 50;
                    break;
                case '2':
                    $type = 'number';
                    $maxlength = 50;
//                    $type = 'select';
//                    $val = $config['datetimeoptions'];
                    break;
                case '3':
                    $type = 'radio';
                    $val = $config['datetimeoptions'];
                    break;
                case '6':
                    $type = 'mobile';
                    $maxlength = 11;
                    break;
                case '0':
                    $type = 'date';
                    break;
                default:
                    break;
            }
            $temp_arr = ['title'=>$config['datetime'],'type'=>$type,'name'=>'datetime','val'=>$val,'placeholder'=>'请输入'.$config['datetime'],'maxlength'=>$maxlength,'final_value'=>''];
            array_push($form,$temp_arr);
        }
        if ($config['address']){
            $type = 'txt';
            $val = '';
            $maxlength = 0;
            switch ($config['addresstype']){
                case '1':
                    $type = 'number';
                    $maxlength = 50;
                    break;
                case '2':
                    $type = 'select';
                    $val = $config['addressoptions'];
                    break;
                case '3':
                    $type = 'radio';
                    $val = $config['addressoptions'];
                    break;
                case '6':
                    $type = 'mobile';
                    $maxlength = 11;
                    break;
                case '7':
                    $type = 'date';
                    break;
                default:
                    break;
            }
            $temp_arr = ['title'=>$config['address'],'type'=>$type,'name'=>'address','val'=>$val,'placeholder'=>'请输入'.$config['address'],'maxlength'=>$maxlength,'final_value'=>''];
            array_push($form,$temp_arr);
        }
        if ($config['formtwo']){
            $type = 'txt';
            $val = '';
            $maxlength = 0;
            switch ($config['formtwotype']){
                case '1':
                    $type = 'number';
                    $maxlength = 50;
                    break;
                case '2':
                    $type = 'select';
                    $val = $config['formtwooptions'];
                    break;
                case '3':
                    $type = 'radio';
                    $val = $config['formtwooptions'];
                    break;
                case '6':
                    $type = 'mobile';
                    $maxlength = 11;
                    break;
                case '7':
                    $type = 'date';
                    break;
                default:
                    break;
            }
            $temp_arr = ['title'=>$config['formtwo'],'type'=>$type,'name'=>'formtwo','val'=>$val,'placeholder'=>'请输入'.$config['formtwo'],'maxlength'=>$maxlength,'final_value'=>''];
            array_push($form,$temp_arr);
        }
        if ($config['addinfo']){
            $type = 'txt';
            $val = '';
            $maxlength = 0;
            switch ($config['addinfotype']){
                case '2':
                    $type = 'number';
                    $maxlength = 50;
                    break;
                case '6':
                    $type = 'mobile';
                    $maxlength = 11;
                    break;
                case '0':
                    $type = 'date';
                    break;
                default:
                    break;
            }
            $temp_arr = ['title'=>$config['addinfo'],'type'=>$type,'name'=>'addinfo','val'=>$val,'placeholder'=>'请输入'.$config['addinfo'],'maxlength'=>$maxlength,'final_value'=>''];
            array_push($form,$temp_arr);
        }
        if ($config['shops']){
            $type = 'txt';
            $val = '';
            $maxlength = 0;
            switch ($config['shopstype']){
                case '2':
                    $type = 'number';
                    $maxlength = 50;
                    break;
                case '0':
                    $type = 'select';
                    $val = $config['shopsoptions'];
                    break;
                case '3':
                    $type = 'radio';
                    $val = $config['shopsoptions'];
                    break;
                case '6':
                    $type = 'mobile';
                    $maxlength = 11;
                    break;
                case '7':
                    $type = 'date';
                    break;
//                case '0':
//                    $type = 'select';
//                    $range_val = $config['options'];
//                    if (!$config['gudingoptions']){
//                        $val = $range_val;
//                    }else{
//                        $guding_val = $config['gudingoptions'];
//                        $val = array_merge($guding_val,$range_val);
//                        $limit_config = ['min'=>$config['shopsmin'],'max'=>$config['shopsmax']];
//                    }
//                    break;

                case '4':
                    $type = 'checkbox';
                    $range_val = $config['shopsoptions'];
                    if (!$config['gudingoptions']){
                        $val = $range_val;
                    }else{
                        $guding_val = $config['gudingoptions'];
                        $val = array_merge($guding_val,$range_val);
                        $limit_config = ['min'=>$config['shopsmin'],'max'=>$config['shopsmax']];
                    }
                    break;
                case '5':
                    $type = 'shop_checkbox';
                    break;
                default:
                    break;
            }
            $temp_arr = ['title'=>$config['shops'],'type'=>$type,'name'=>'shops','val'=>$val,'placeholder'=>'请输入'.$config['shops'],'limit_config'=>$limit_config,'final_value'=>''];
            array_push($form,$temp_arr);
        }
        //组装数组
        $buy_button = str_replace('#fee', $config['groupprice'], $config['formtextpay']);
        if (empty($config['wk_gift_bags'])){
            $config['wk_gift_bags'] = [];
        }
        $wk_gift_bags = array_chunk($config['wk_gift_bags'],4);
        $data = [
            'wk_gift_bag_bg'=>$config['wk_gift_bag_bg'],//特权礼包背景图
            'wk_gift_bags'=>$wk_gift_bags,//特权礼包内容
            'wk_time_bg'=>$config['wk_time_bg'],//倒计时背景图
            'wk_buy_limit'=>$limit,//领取礼包限量配置
            'wk_buy_button_tips'=>$config['wk_buy_button_tips'],//支付按钮下方提示
            'form_info'=>$form,//使用贝莱逻辑
            'buy_button'=>$buy_button,//报名支付按钮
            'over_button'=>'来迟了，领光了',
            'has_buy_button'=>'您已领取',
            'has_buy'=>$has_buy,
            'can_buy'=>$can_buy,
            'buy_list'=>$buy_list,
            'buy_num'=>$buy_num,
//            'config'=>$config,
            'jishu' => Worker::getjishu($theme,$system),
            'jubf'=>$theme['jubf'],
        ];
        return_json(0,'',$data);
    }

    //3、礼物接口：送礼物列表、礼物配置信息
    function giftInfo(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        $wk_id = intval($_P['wk_id'])?:0;
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息');
        }
        $wkUserInfo = db_get(t_fans, ['themeid' => $themeid, 'uid' => $wkInfo['uid']]);
        //是否是员工
        $isWorker = is_worker($themeid);
        $wk_config = $wkInfo['config'];
        //查找送礼总数，列表：头像、昵称、礼物名称、礼物图标
        $gift_list = WeikeModel::getGiveGiftList($themeid,$wk_id);
        $gift_num = count($gift_list);
        //查找礼物列表：icon，金额、名称、id
        $gift_infos = WeikeModel::getGiftList($wk_config['wk_gift_group_id']);
        //打call图标插入数组，先使用默认，array_unshift();
        $show_money = true;
        if (empty($gift_infos) || !$config['wk_gift_open']){
            $gift_infos = [];
            $show_money = false;
        }
        if($config['wk_call_open']){
            array_unshift($gift_infos,['id'=>0,'title'=>'CALL','price'=>0,'icon'=>'https://css2020.yixuan.net/2020css/weike/images/icon_like@2x.png','status'=>1]);
        }
        foreach ($gift_infos as &$v){
            $v['price'] = floatval($v['price']);
        }
        $gift_info_list = array_chunk($gift_infos,8);
        //客服信息和海报
        if($wk_config['workerid']){
            $isworker = Worker::getThemeWorkerByUid(intval($wk_config['workerid']),$themeid,1);
        }else if(intval($_P['workerid'])){
            $isworker = Worker::getThemeWorkerByUid(intval($_P['workerid']),$themeid,1);
        }else{
            $isworker = Worker::getThemeWorkerByUid($fans['workerid'],$themeid,1);
        }
        $kefu = ['qr_code'=>$isworker['qrcode']?:$config['kfewm'],'mobile'=>$isworker['mobile']?:$theme['mobile'],'avatar'=>$isworker['avatar'],'name'=>$isworker['username'],];
//        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid);
        //组装数组返回数据
        $data = [
            'wk_gift_unit'=>$config['wk_gift_unit'],//打赏礼物单位
            'wk_gift_rules'=>$config['wk_gift_rules'],//礼物规则
            'name'=>$wkInfo['name'],
            'gift_list'=>$gift_list,
            'gift_num'=>$gift_num,
            'gift_infos'=>$gift_info_list,
            'avatar'=>$wkUserInfo['avatar'],
            'kefu'=>$kefu,
//            'myworker'=>$myworker,
            'company_mobile'=>$config['mobile'],
            'show_money'=>$show_money,
        ];
        return_json(0,'',$data);
    }
    //4、送礼物接口：打call和打赏，涉及支付
    function giveCall(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        $wk_id = intval($_P['wk_id'])?:0;
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息');
        }
        if ($wkInfo['has_case_gift']){
            return_json(1,'您的好友集call已完成！');
        }
        //是否是员工
        $isWorker = is_worker($themeid);
        if ($isWorker && !$config['wk_worker_call_type']){
            return_json(1,'员工不允许打call！');
        }
        //礼物ID
        $gift_id = intval($_P['gift_id'])?:0;
        if ($gift_id == 0){
            //查找用户打call记录，判断规则限制 $config['wk_call_type']
            if($uid == $wkInfo['uid']){
                return_json(1,'无法为自己打call');
            }
            $start = '';
            $end = '';
            if ($config['wk_call_type'] == 0){
                //每人每天打call一次
                $start = date('Y-m-d').' 00:00:00';
                $end = date('Y-m-d').' 23:59:59';
            }
            $call_info = WeikeModel::getCallRecords($themeid,$wk_id,$uid,$start,$end);
            if (!empty($call_info)){
                return_json(1,'您已经为TA打过CALL');
            }
            $data = [
                'themeid'=>$themeid,
                'from_uid'=>$uid,
                'to_uid'=>$wkInfo['uid'],
                'wk_id'=>$wk_id,
                'created_at'=>date("Y-m-d H:i:s"),
            ];
            //存入数据库
            $res = WeikeModel::insertCallRecordData($data);
            if (!$res){
                return_json(1,'打call失败');
            }else{
                //打call数+1
                //修改数据库字段
                $sql = "UPDATE ".tablename(wk_info)." SET call_num = call_num+1 WHERE id = $wk_id AND themeid = $themeid";
                WeikeModel::pdoQuery($sql);
                return_json(0,'打call成功');
            }
        }else{
            return_json(1,'非法请求！');
        }
    }

    //5、收集客资信息
    function collectUserInfo(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        $wk_id = intval($_P['wk_id'])?:0;
        $collect_type = trim($_P['collect_type'])?:'call';
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息');
        }
        if($uid == $wkInfo['uid']){
            return_json(0,'成功');
        }
        $wk_config = $wkInfo['config'];
        $collectIds = $wk_config['collect_ids']?:[];
        $giftCollectIds = $wk_config['gift_collect_ids']?:[];
        if ($collect_type == 'gift'){
            if ($uid && $wkInfo['uid'] && !in_array($uid,$giftCollectIds)){
                //执行写入
                array_push($giftCollectIds,$uid);
                $wk_config['gift_collect_ids'] = $giftCollectIds;
                $config_str = json_encode($wk_config,JSON_UNESCAPED_UNICODE);
                $sql = "UPDATE ".tablename(wk_info)." SET gift_collect_num = gift_collect_num+1,config = '$config_str' WHERE id = $wk_id AND themeid = $themeid";
                $add_res = WeikeModel::pdoQuery($sql);
                if($add_res){
                    //写入收集信息表中
                    return_json(0,'成功');
                }else{
                    return_json(1,'失败');
                }
            }
            return_json(0,'成功');
        }elseif ($collect_type == 'call'){
            if ($uid && $wkInfo['uid'] && !in_array($uid,$collectIds)){
                //执行写入
                array_push($collectIds,$uid);
                $wk_config['collect_ids'] = $collectIds;
                $config_str = json_encode($wk_config,JSON_UNESCAPED_UNICODE);
                $sql = "UPDATE ".tablename(wk_info)." SET collect_num = collect_num+1,config = '$config_str' WHERE id = $wk_id AND themeid = $themeid";
                $add_res = WeikeModel::pdoQuery($sql);
                if($add_res){
                    //写入收集信息表中
                    return_json(0,'成功');
                }else{
                    return_json(1,'失败');
                }
            }
            return_json(0,'成功');
        }
    }

    //6、核销礼品
    function checkCallGift()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求',['jubf'=>'']);
        }
        $config = $_C;
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确',['jubf'=>'']);
        }
        $jubf =$theme['jubf'];
        //是否是员工
        $isWorker = is_worker($themeid);
        if(!$isWorker){
            return_json(1,'您没有员工权限',['jubf'=>$jubf]);
        }
        $wk_id = intval($_P['wk_id'])?:0;
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息',['jubf'=>$jubf]);
        }
        $gift_id = intval($_P['gift_id'])?:0;
        $giftInfo = WeikeModel::getCallGiftInfoByWhere($gift_id);
        if (empty($giftInfo)){
            return_json(1,'未找到礼品信息',['jubf'=>$jubf]);
        }
        //判断实际打call数与奖品限制
        $call_nums = WeikeModel::getCallRecordList($themeid,$wk_id, '', 0, 0);
        if($call_nums['count_num'] < $giftInfo['num_limit']){
            return_json(1,'打call数量未达到兑换礼品要求！',['jubf'=>$jubf]);
        }
        $wk_config = $wkInfo['config'];
        if($wkInfo['has_case_gift']){
            //查找兑换信息，拼接提示字符串 case_gift_id
            $tip_desc = '错误：已于'.$wk_config['case_gift_time'].'由本公司'.$wk_config['case_gift_worker'].'核销过';
            return_json(1,$tip_desc,['jubf'=>$jubf]);
        }
        $workerInfo = Worker::getThemeWorkerByUid($uid,$themeid,1);
        $wk_config['case_gift_worker'] = $workerInfo['username'];
        $wk_config['case_gift_workerid'] = $uid;
        $wk_config['case_gift_time'] = date('Y-m-d h:i:s');
        $wk_config['case_gift_id'] = $gift_id;
        $wk_config['case_gift_name'] = $giftInfo['title'];
        $wk_config['case_gift_img'] = $giftInfo['content'];
        $res = WeikeModel::editWkDataByWhere(['id'=>$wk_id],['has_case_gift'=>1,'config'=>json_encode($wk_config,JSON_UNESCAPED_UNICODE)]);
        if ($res){
            return_json(0,'兑换成功！',['jubf'=>$jubf]);
        }
        return_json(1,'兑换失败！',['jubf'=>$jubf]);
    }

    //7、获取微客信息
    function getWkInfo(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        //是否是员工
        $isWorker = is_worker($themeid);
        if(!$isWorker){
            return_json(1,'您没有员工权限');
        }
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
        $wk_id = intval($_P['wk_id'])?:0;
        if(!$wk_id){
            $workerid = 0;
            $wlist = Worker::getworkerlist($system,$themeid);
            $worker_index = -1;
            $worker_name = '未选择员工';
            $jubf['title'] = empty($theme['jubf'])?'':$theme['jubf'].'-';
            $jubf['banquan'] = !empty($theme['USERCOMPANYNAME'])?$theme['USERCOMPANYNAME']:$_G['companyname'];
            if($myworker['level'] == 3){
                $workerid = $myworker['uid'];
                foreach ($wlist as $key=>$val){
                    if ($workerid == $val['uid']){
                        $worker_index = $key;
                        $worker_name = $val['teamname']?$val['teamname'].'-'.$val['username']:$val['username'];
                    }
                }
            }
            $result = array(
                'jubf' => $jubf,
                'workerid' => $workerid,
                'worker_index' => $worker_index,
                'worker_name'=> $worker_name,
                'worker_list' => $wlist,
                'myworker'=>$myworker,
            );
            return_json(0,'',$result);
        }
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息');
        }
        $wk_config = $wkInfo['config'];
        $wk_url = $wk_config['wk_url']?:'';
        if(!$wk_url){
            //请求生成小程序码，参数待定；
            $theme = Theme::getThemeById($themeid);
            $scene = MODULE_NAME . "-" . $themeid . "-w" . $wk_id . "-" .$theme['softkey']. "-" . 0;
            $qrcode = Poster::CreateScene($system,$scene,$config,'weike/pages/weike/weike');
            $wk_config['wk_url'] = $qrcode;
            $wk_url = $qrcode;
            WeikeModel::editWkDataByWhere(['id'=>$wk_id],['config'=>json_encode($wk_config)]);
        }
        $workerid = $wk_config['workerid']?:0;
        $wlist = Worker::getworkerlist($system,$themeid);
        $worker_index = -1;
        $worker_name = '未选择员工';
        foreach ($wlist as $key=>$val){
            if ($workerid == $val['uid']){
                $worker_index = $key;
                $worker_name = $val['teamname']?$val['teamname'].'-'.$val['username']:$val['username'];
            }
        }
        $wkUserInfo = db_get(t_fans, ['themeid' => $themeid, 'uid' => $wkInfo['uid']]);
        $music_src = $wk_config['music_src']?:'';
        $music_id = $wk_config['music_id']?:0;
        $music_index = -1;
        $music_name = '未选择音乐';
        $music_list = WeikeModel::getMusicList($themeid);
        foreach ($music_list as $key=>$val){
            if ($music_id == $val['id']){
                $music_index = $key;
                $music_name = $val['name'];
                $music_src = $val['url'];
            }
        }
        //查找礼品组
        $wk_call_gift_group_id = $wk_config['wk_call_gift_group_id']?:0;
        $wk_call_gift_group_index = -1;
        $wk_call_gift_group_name = '未选择打call礼品';
        $wk_call_gift_groups = WeikeModel::getCallGiftGroups($themeid,false);
        foreach ($wk_call_gift_groups as $key=>$val){
            if ($wk_call_gift_group_id == $val['id']){
                $wk_call_gift_group_index = $key;
                $wk_call_gift_group_name = $val['title'];
            }
        }
        //查找礼物组
        $wk_gift_group_id = $wk_config['wk_gift_group_id']?:0;
        $wk_gift_group_index = -1;
        $wk_gift_group_name = '未选择打赏礼物';
        $wk_gift_groups = WeikeModel::getGiftGroups($themeid,false);
        foreach ($wk_gift_groups as $key=>$val){
            if ($wk_gift_group_id == $val['id']){
                $wk_gift_group_index = $key;
                $wk_gift_group_name = $val['title'];
            }
        }
        $jubf['title'] = empty($theme['jubf'])?'':$theme['jubf'].'-';
        $jubf['banquan'] = !empty($theme['USERCOMPANYNAME'])?$theme['USERCOMPANYNAME']:$_G['companyname'];
        $result = array(
//            'system' => $system,
//            'theme' => $theme,
//            'config' => $config,
            'fans' => $fans,
            'themeid' => $themeid,
            'myworker' => $myworker,
            'jubf' => $jubf,
            'jishu' => Worker::getjishu($theme,$system),
            'wk_info' => $wkInfo,
            'wk_url' => $wk_url,
            'workerid' => $workerid,
            'worker_index' => $worker_index,
            'worker_name'=> $worker_name,
            'worker_list' => $wlist,
            'wk_user_info' => $wkUserInfo,
            'music_src' => $music_src,
            'music_id' => $music_id,
            'music_index' => $music_index,
            'music_name'=> $music_name,
            'music_list' => $music_list,
            'wk_call_gift_group_id' => $wk_call_gift_group_id,
            'wk_call_gift_group_index' => $wk_call_gift_group_index,
            'wk_call_gift_group_name'=> $wk_call_gift_group_name,
            'wk_call_gift_groups' => $wk_call_gift_groups,
            'wk_gift_group_id' => $wk_gift_group_id,
            'wk_gift_group_index' => $wk_gift_group_index,
            'wk_gift_group_name'=> $wk_gift_group_name,
            'wk_gift_groups' => $wk_gift_groups,
        );
        return_json(0,'',$result);
    }

    //8、增加客片
    function addWkInfo(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        //是否是员工
        $isWorker = is_worker($themeid);
        if(!$isWorker){
            return_json(1,'您没有员工权限');
        }
        $wk_id = intval($_P['wk_id']);
        $name = trim($_P['name'])?:'';
        $show_type = intval($_P['show_type'])?:0;
        if (empty($name)){
            return_json(1,'姓名不能为空！');
            return;
        }
        if (empty($_P['photos'])){
            return_json(1,'请上传照片！');
            return;
        }
        //处理图片
        $photos = [];
        $g_photos =$_P['photos'];
        foreach ($g_photos as $v){
            $photos[]=tomedia($v);
        }
        $share_img = $_P['share_img']?tomedia($_P['share_img']):'';
        $workerid = $_P['worker_id']?:0;
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
        if($myworker['level'] == 3){
            $workerid = $myworker['uid'];
        }
        if(!$workerid){
            return_json(1,'请选择员工！');
            return;
        }
        $music_id = $_P['music_id']?:0;
        $music_src = $_P['music_src']?:'';
        if($wk_id){
            //编辑
            //根据ID查找信息
            $info = WeikeModel::getWkInfoById($wk_id,$themeid);
            if(empty($info)){
                return_json(1,'未找到客片信息');
                return;
            }
            $data = [
                'name'=>$name,
                'call_num'=>intval($_P['call_num'])?:0,
                'gift_num'=>intval($_P['gift_num'])?:0,
                'money'=>floatval($_P['money'])?:0,
            ];
            $old_config = $info['config'];
            $call_gift_group_id = intval($_P['wk_call_gift_group_id']);
            if ($call_gift_group_id == 0){
                $call_gift_group_id = $old_config['wk_call_gift_group_id'];
            }
            $wk_gift_group_id = intval($_P['wk_gift_group_id']);
            if ($wk_gift_group_id == 0){
                $wk_gift_group_id = $old_config['wk_gift_group_id'];
            }
            if ($_P['end_time'] < $_P['start_time']){
                return_json(1,'结束时间不能小于开始时间');
                return;
            }
            $wk_config = $old_config;
            $wk_config['photo'] = $photos;
            $wk_config['show_type'] = $show_type;
            $wk_config['start_time'] = $_P['start_time'];
            $wk_config['end_time'] = $_P['end_time'];
            $wk_config['wk_call_gift_group_id'] = $call_gift_group_id;
            $wk_config['wk_gift_group_id'] = $wk_gift_group_id;
            $wk_config['shareimg'] = $share_img;
            $wk_config['workerid'] = $workerid;
            $wk_config['music_id'] = $music_id;
            $wk_config['music_src'] = $music_src;
            $data['config'] = json_encode($wk_config);
            $where = ['id'=>$wk_id,'themeid'=>$themeid];
            //修改数据库字段
            $res = WeikeModel::editWkDataByWhere($where,$data);
            if (!$res){
                return_json(1,'操作失败');
            }else{
                return_json(0,'操作成功');
            }
        }else{
            //新增
            //查找config中配置天数，计算开始时间和结束时间
            $days = $config['wk_call_days']?:10;
            $start_time = date('Y-m-d');
            $end_time = date('Y-m-d',strtotime("+ $days days"));
            if ($end_time < $start_time){
                return_json(1,'结束时间不能小于开始时间');
                return;
            }
            //礼物和礼品分组ID
            $call_gift_group_id = intval($_P['wk_call_gift_group_id'])?:$config['wk_call_gift_group_id'];
            if ($call_gift_group_id == 0){
                //查找数据，取值最新的
                $call_gift_groups = WeikeModel::getCallGiftGroups($themeid);
                if (!empty($call_gift_groups)){
                    $call_gift_group_id = $call_gift_groups['id'];
                }
            }
            $wk_gift_group_id = intval($_P['wk_gift_group_id'])?:$config['wk_gift_group_id'];
            if ($wk_gift_group_id == 0){
                //查找数据，取值最新的
                $gift_groups = WeikeModel::getGiftGroups($themeid);
                if (!empty($gift_groups)){
                    $wk_gift_group_id = $gift_groups['id'];
                }
            }
            //随机取音乐
            $music_list = WeikeModel::getMusicList($themeid);
            if(!empty($music_list)){
                $index = array_rand($music_list);
                $music_id = $music_list[$index]['id'];
                $music_src = $music_list[$index]['url'];
            }
            //show_type 取值config
            $show_type = isset($config['wk_photo_show_type'])?intval($config['wk_photo_show_type']):0;
            //拼接数组
            $data = [
                'themeid'=>$themeid,
                'name'=>$name,
                'call_num'=>0,
                'gift_num'=>0,
                'money'=>0,
                'page_view'=>0,
                'delete'=>0,
            ];
            $wk_config = [
                'photo'=>$photos,
                'show_type'=>$show_type,
                'start_time'=>$start_time,
                'end_time'=>$end_time,
                'wk_call_gift_group_id'=>$call_gift_group_id,
                'wk_gift_group_id'=>$wk_gift_group_id,
                'arecord_ids'=>array(),//报名支付成功ID数组暂定为空数组
                'shareimg'=>$share_img,
                'workerid'=>$workerid,
                'music_id'=>$music_id,
                'music_src'=>$music_src,
            ];
            $data['config'] = json_encode($wk_config);
            //存入数据库
            $res = WeikeModel::insertWkData($data);
            if (!$res){
                return_json(1,'操作失败');
            }else{
                return_json(0,'操作成功',['wk_id'=>$res]);
            }
        }
    }

    //9、重新绑定
    function removeBind(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        //是否是员工
        $isWorker = is_worker($themeid);
        if(!$isWorker){
            return_json(1,'您没有员工权限');
        }
        $wk_id = intval($_P['wk_id'])?:0;
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息');
        }
        if (!$wkInfo['uid']){
            return_json(1,'微客未绑定！');
        }
        $data['uid'] = 0;
        $where = ['id'=>$wk_id,'themeid'=>$themeid];
        //修改数据库字段
        $res = WeikeModel::editWkDataByWhere($where,$data);
        if (!$res){
            return_json(1,'操作失败');
        }else{
            return_json(0,'操作成功');
        }
    }
    function resetCode(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        //是否是员工
        $isWorker = is_worker($themeid);
        if(!$isWorker){
            return_json(1,'您没有员工权限');
        }
        $wk_id = intval($_P['wk_id'])?:0;
        $wkInfo = WeikeModel::getWkInfoById($wk_id,$themeid);
        if (empty($wkInfo)){
            return_json(1,'未找到微客信息');
        }
        //重新生成小程序码并更新
        $wk_config = $wkInfo['config'];
        //请求生成小程序码，参数待定；
        $theme = Theme::getThemeById($themeid);
        $scene = MODULE_NAME . "-" . $themeid . "-w" . $wk_id . "-" .$theme['softkey']. "-" . 0;
        $qrcode = Poster::CreateScene($system,$scene,$config,'weike/pages/weike/weike');
        $wk_config['wk_url'] = $qrcode;
        //修改数据库字段
        $res = WeikeModel::editWkDataByWhere(['id'=>$wk_id,'themeid'=>$themeid],['config'=>json_encode($wk_config)]);
        if (!$res){
            return_json(1,'操作失败');
        }else{
            return_json(0,'操作成功');
        }
    }

    //10、获取客片列表数据：客片总数、已绑定客片、已兑换礼品
    function getWkList(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        //是否是员工
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
        if (empty($myworker) || $myworker['level']>3) {
            return_json(1,'您没有员工权限');
        }
        $workerid = 0;
        if($myworker['level'] == 3){
            $workerid = $uid;
        }
//        if($myworker['level'] == 3){
            //select * from yx_yx18906_wk_info where config->'$.workerid' = '1655';
//        }
        $page_index = max(1,intval($_P['page']));
        $page_size = 5;
        $page_start = ($page_index-1)*$page_size;
        $search_data = isset($_P['searchtxt'])?$_P['searchtxt']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }
        $scan = intval($_P['scan'])?:0;
        $wk_list = WeikeModel::getWeikeList($themeid,$search_data,$page_start,$page_size,$scan,$workerid);
        $count = WeikeModel::getWeikeList($themeid,$search_data,0,0,$scan,$workerid);
        $total = $count['count_num'];
        $list = [];
        foreach ($wk_list as &$item){
            $wk_config = json_decode($item['config'],true);
            $workerInfo = Worker::getThemeWorkerByUid($wk_config['workerid'],$themeid,1);
            $item['worker'] = $workerInfo;
            if($item['uid']>0){
                $item['moreinfo'][] = '昵称：'.$item['nickname'];
            }
            $item['moreinfo'][] = '销售：'.$workerInfo['nickname'];
            $left_days = (strtotime($wk_config['end_time'])-strtotime(date('Y-m-d')))/(3600*24);
            if($left_days > 0){
//                $item['moreinfo'][] = '剩余天数：'.$left_days;
                $item['left_day'] = $left_days;
//                $item['left_day_desc'] = '剩余：'.$left_days.'天';
            }else{
//                $item['moreinfo'][] = '剩余天数：已结束';
                $item['left_day'] = 0;
//                $item['left_day_desc'] = '已结束';
            }
            $item['moreinfo'][] = '结束日期：'.$wk_config['end_time'];
            $item['config'] = $wk_config;
            $can_case_gift = '暂无';
            if($item['call_num'] > 0){
                //查找groupid下礼品
                $gift_lists = WeikeModel::getCallGiftListByWhere($wk_config['wk_call_gift_group_id'],$item['call_num']);
                if(!empty($gift_lists)){
                    $name_list = array_column($gift_lists,'title');
                    $can_case_gift = implode("，",$name_list);
                }
            }
            $item['moreinfo'][] = '可兑换礼品：'.$can_case_gift;

            if($item['has_case_gift']){
                //查找兑换gift_name
                $item['moreinfo'][] = '已兑换礼品：'.$wk_config['case_gift_name'];
                $item['moreinfo'][] = '兑换日期：'.$wk_config['case_gift_time'];
                $item['moreinfo'][] = '兑换员工：'.$wk_config['case_gift_worker'];
            }else{
                $item['moreinfo'][] = '已兑换礼品：未兑换';
            }
            $canEdit = false;
            if($myworker['level'] < 3 || $uid == $wk_config['workerid']){
                $canEdit = true;
            }
            $item['canEdit'] = $canEdit;
            $collect_ids = [];
            if($wk_config['collect_ids'] && !empty($wk_config['collect_ids'])){
                $collect_ids = $wk_config['collect_ids'];
            }
            $gift_collect_ids = [];
            if($wk_config['gift_collect_ids'] && !empty($wk_config['gift_collect_ids'])){
                $gift_collect_ids = $wk_config['gift_collect_ids'];
            }
            $all_collect = array_merge($collect_ids,$gift_collect_ids);
            $new_collect = array_unique($all_collect);
            $uids = '';
            if(!empty($new_collect)){
                $uids = implode(",",$new_collect);
            }
            $item['collect_num'] = count($new_collect);
            $item['collect_uids'] = $uids;

            $list[] = $item;
        }
        $jubf['title'] = empty($theme['jubf'])?'':$theme['jubf'].'-';
        $jubf['banquan'] = !empty($theme['USERCOMPANYNAME'])?$theme['USERCOMPANYNAME']:$_G['companyname'];
        $jishu = Worker::getjishu($theme,$system);
        $hasNext = false;
        if(intval($_P['page'])*$page_size < $total){
            $hasNext = true;
        }
        $where = '';
        if($workerid){
            $where = " AND a.config->'$.workerid' = '$workerid' ";
        }
        $all = WeikeModel::getWeikeCountByWhere($themeid,$where);
//        $bindall = WeikeModel::getWeikeCountByWhere($themeid,' AND a.uid>0 '.$where);
//        $caseall = WeikeModel::getWeikeCountByWhere($themeid,' AND a.has_case_gift=1 '.$where);
        $unbindall = WeikeModel::getWeikeCountByWhere($themeid,' AND a.uid=0 '.$where);
        $uncaseall = WeikeModel::getWeikeCountByWhere($themeid,' AND a.has_case_gift=0 '.$where);
        $today = date('Y-m-d');
        $unendall = WeikeModel::getWeikeCountByWhere($themeid," AND a.config->'$.end_time' >= '$today' ".$where);
        //顶部数据项 1 总数 2 已绑定 3 已兑换 4 未绑定 5未兑换 6 进行中
        $top_data = [
            ['id'=>1,'name'=>'总数','num'=>$all],
            ['id'=>4,'name'=>'未绑定','num'=>$unbindall],
            ['id'=>5,'name'=>'未兑换','num'=>$uncaseall],
            ['id'=>6,'name'=>'进行中','num'=>$unendall],
        ];

        return_json(0,'',
            [
                'top_data'=>$top_data,
                'list'=>$list,
                'jubf'=>$jubf,
                'jishu'=>$jishu,
                'page'=>intval($_P['page']),
                'hasNext'=>$hasNext,
                'system'=>$system,
                'wk_call_open'=>$config['wk_call_open'],
                'wk_gift_open'=>$config['wk_gift_open'],
            ]
        );
    }

    //11、获取打call列表
    function getCallList(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
        }
        $config = $_C;
        $system = $_S;
        $fans = $this->check_mini_user();
        $uid = $fans['uid']?:0;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        //是否是员工
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
        if (empty($myworker) || $myworker['level']>3) {
            return_json(1,'您没有员工权限');
        }
        $workerid = 0;
        if($myworker['level'] == 3){
            $workerid = $uid;
        }
        $page_index = max(1,intval($_P['page']));
        $page_size = 15;
        $page_start = ($page_index-1)*$page_size;
        $type = trim($_P['op'])?:'call';
        $wk_id = intval($_P['wk_id'])?:0;
        if($type == 'call'){
            $list = WeikeModel::getCallRecordList($themeid,$wk_id,'',$page_start,$page_size,$workerid);
            $count = WeikeModel::getCallRecordList($themeid,$wk_id,'',0,0,$workerid);
        }else{
            $list = WeikeModel::getGiftRecordList($themeid,$wk_id,'',$page_start,$page_size,$workerid);
            $count = WeikeModel::getGiftRecordList($themeid,$wk_id,'',0,0,$workerid);
        }
        $total = $count['count_num'];
        $jubf['title'] = empty($theme['jubf'])?'':$theme['jubf'].'-';
        $jubf['banquan'] = !empty($theme['USERCOMPANYNAME'])?$theme['USERCOMPANYNAME']:$_G['companyname'];
        $jishu = Worker::getjishu($theme,$system);
        $hasNext = false;
        if(intval($_P['page'])*$page_size < $total){
            $hasNext = true;
        }
        if (!empty($list)){
            foreach ($list as &$item){
                if (mb_strlen($item['nickname']) > 6){
                    $item['nickname'] = mb_substr($item['nickname'],0,6).'...';
                    if (empty($item['nickname'] || $item['nickname'] == null)){
                        $item['nickname'] = '';
                    }
                    if (empty($item['avatar'] || $item['avatar'] == null)){
                        $item['avatar'] = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
                    }
                }
                //礼物名称截取
            }
        }
        return_json(0,'',
            [
                'list'=>$list,
                'jubf'=>$jubf,
                'jishu'=>$jishu,
                'page'=>intval($_P['page']),
                'hasNext'=>$hasNext,
                'system'=>$system,
                'showType'=>$config['wk_show_friend_info_type'],
            ]
        );
    }

    function giveGift(){
        global $_G, $_P;
        $fans = $this->check_mini_user();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeByIdxcx($themeid);
        if (empty($theme['id'])) {
            return_json(1,'活动入口不正确');
            exit;
        }
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp'){
            return_json(1,'非法请求');
            exit;
        }
        $config = Theme::getConfig($themeid);
        $gift_id = intval($_P['gift_id']);
        $wk_id = intval($_P['wk_id']);

        //未支付的进行较验是否已支付
        Order::checkorder($themeid, $config, $system);
        //Userdata::addLog($themeid, $_G['member']['uid'], 6);

        if ($theme['status'] == 0) {
            return_json(1, '活动未开始');
            exit;
        }
        if ($theme['status'] == 2) {
            return_json(1, '活动已结束');
            exit;
        }
        //Ad::saveMBXX(); //保存模版消息

        $wkInfo = db_find("select * from ". tablename(wk_info) ." where id=$wk_id and themeid=$themeid");
        $wk_config = json_decode($wkInfo['config'],true);
        $wk_gift_group_id = $wk_config['wk_gift_group_id'];

        $fee = 0;
        //查找礼物信息，包含金额
        $sql = "SELECT * FROM " . tablename(wk_gift) . " WHERE id = $gift_id and group_id=$wk_gift_group_id";
        $giftInfo = db_find($sql);
        if (empty($giftInfo)){
            return_json(1, '未找到礼物信息！');
            exit;
        }
        $fee = floatval($giftInfo['price']);
        //查找分组信息的themeid是否与传参匹配
        $sql1 = "SELECT * FROM " . tablename(wk_gift_group) . " WHERE id = ".$wk_gift_group_id;
        $row1 = db_find($sql1);
        if (empty($row1)){
            return_json(1, '未找到礼物分组信息！');
            exit;
        }
        if (intval($row1['themeid']) != $themeid){
            return_json(1, '活动信息与礼物分组信息不匹配！');
            exit;
        }
        if ($fee <= 0) {
            return_json(1, '打赏礼物金额不可为0元');
            exit;
        }
        //写入赠送礼物记录表
        //查找礼物信息
        $uid = $_G['member']['uid'];
//        if ($uid == $wkInfo['uid']){
//            return_json(1, '不可以给自己打赏礼物');
//            exit;
//        }
        $record_data = [
            'themeid'=>$themeid,
            'wk_id'=>$wk_id,
            'from_uid'=>$uid,
            'to_uid'=>$wkInfo['uid'],
            'gift_id'=>$gift_id,
            'price'=>$fee,
            'status'=>0,
            'pay_info'=>json_encode(array()),
            'created_at'=>date("Y-m-d H:i:s"),
            'updated_at'=>date("Y-m-d H:i:s"),
        ];
        //存入数据库
        $record_res = $insertid = db_insert(wk_give_gift_record,$record_data);
        if (empty($record_res)){
            return_json(1, '打赏记录失败！');
            exit;
        }
        $record_id = $insertid;
        if (!$record_id){
            return_json(1, '未找到记录信息！');
            exit;
        }
        //组装数组
        $data = array(
            'uniacid' => $_G['mpid'],
            'ordertype' => 100,//暂定义为类型100为打赏礼物
            'themeid' => $themeid,
            'openid' => $_G['openid'],
            'uid' => $uid,
            'username' => $fans['username'],
            'mobile' => $fans['mobile'],
            'status' => 0,
            'type' => 'wxapp',
        );
        $data['orderfee'] = $fee;
        $data['masterid'] = $wk_id;//主id为微客id
        $data['detailid'] = $record_id;//详细id为记录id
        $orderid = 0;
        $tid = '';
        $billcode = getMillisecond();
        $tid = '0' . $billcode;
        $data['tid'] = $tid;
        $data['addtime'] = TIMESTAMP;
        $data['ordersn'] = $billcode;
        $orderid = Order::save($data);

        $ordertype = 'theme';

        if (empty($_G['openid']) || empty($_G['member']['uid'])) {
            return_json(1, '用户信息错误');
            return;
        }
        $order = Order::getByIdAndOpenid($orderid, $_G['openid']);
        if (empty($order)) {
            return_json(1, '记录不存在，请重新下单');
            exit;
        }
        if ($order['status'] != 0) {
            return_json(1, '定单已完成支付');
            exit;
        }
        if ($order['orderfee'] <= 0) {
            return_json(1, '金额必须大于0元');
            exit;
        }

        //调用微信支付
        $desclen = 26;
        $theme = Theme::getThemeById($order['themeid']);
        if (!empty($theme['mobile'])) {
            $desc = "【客服" . $theme['mobile'] . "】";
            $desclen = $desclen - mb_strlen($desc);
        }
        if (!empty($theme['jubf'])) {
            $desc = mb_substr($theme['jubf'], 0, $desclen, "UTF-8") . $desc;
        } else {
            $desc = mb_substr($theme['title'], 0, $desclen, "UTF-8") . $desc;
        }
        $title = $desc;

        $params = array('isrecharge' => false);
        //不是分账模式
        //if ($system['send_mode'] == 1) {
        //    $params ['profit_sharing'] = 'Y';
        //}
        $params ['tid'] = $order['tid'];
        $params ['user'] = $_G['openid'];
        $params ['fee'] = $order['orderfee'];
        $params ['title'] = $title;
        $params ['ordersn'] = $order['ordersn'];
        $params ['virtual'] = false;
        $this->helppay($params);
        $pay_params = $this->pay($params);
//        var_dump($pay_params);die();
        if (is_error($pay_params)) {
            return return_json(1, '支付失败，请重试', $pay_params);
        }
        return return_json(0, '', $pay_params);
    }

    public function helppay($params){
        global $_G;
        $log = db_get('yx_sys_paylog', array('mpid' => $_G['mpid'], 'module' => MODULE_NAME, 'tid' => $params['tid']));
        //在pay方法中，要检测是否已经生成了paylog定单记录，如果没有需要插入一条定单数据
        //未调用系统pay方法的，可以将此代码放至自己的pay方法中，进行漏洞修复
        if (empty($log)) {
            $log = array(
                'uniacid' => $_G['mpid'],
                'acid' => $_G['acid'],
                'openid' => $_G['member']['uid'],
                'module' => MODULE_NAME, //模块名称，请保证$this可用
                'tid' => $params['tid'],
                'fee' => $params['fee'],
                'card_fee' => $params['fee'],
                'status' => '0',
                'is_usecard' => '0',
            );
            $insertid = db_insert('core_paylog', $log);
        }
    }
}